using FastDevTemplate.DataAccess.Base;

namespace FastDevTemplate.DataAccess.Entities;

public class User : AuditEntity<Guid>
{
    public string UserName { get; set; } = "";
    public string Password { get; set; } = "";
    public long LoginAt { get; set; }
    public long OprationAt { get; set; }
    public ICollection<UserRole> UserRoles { get; set; } = new List<UserRole>();

    public void ToLoginState()
    {
        var nowDataTime = GetNowTimeSpan();
        LoginAt = nowDataTime;
        OprationAt = nowDataTime;
    }

    // public User SetRoles(params string[] roleKeys)
    // {
    //     UserRoles = new List<UserRole>();
    //     foreach (var roleIDs in roleKeys)
    //         UserRoles.Add(new UserRole
    //         {
    //             UserID = ID,
    //             RoleID = roleIDs
    //         });
    //     return this;
    // }

    public User AddRole(params string[] roleIDs)
    {
        foreach (var id in roleIDs)
            if (UserRoles.All(item => item.RoleID != id))
                UserRoles.Add(new UserRole
                {
                    UserID = ID,
                    RoleID = id
                });
        return this;
    }

    public User RemoveRole(params string[] roleIDs)
    {
        foreach (var id in roleIDs)
        {
            var role = UserRoles.FirstOrDefault(item => item.RoleID == id);
            if (role != null)
                UserRoles.Remove(role);
        }

        return this;
    }

    public User SetRoles(params string[] roleIDs)
    {
        UserRoles.Clear();
        foreach (var id in roleIDs)
            UserRoles.Add(new UserRole
            {
                UserID = ID,
                RoleID = id
            });
        return this;
    }
}

public class UserRole
{
    public Guid UserID { get; set; }
    public string RoleID { get; set; } = "";

    public User User { get; set; }
    public Role Role { get; set; }
}